package com.ubi.core.framework.response;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

/**
 * 对返回对象的统一封装类，可统一处理返回值header. <br>
 * 类详细说明.
 * int httpStatus = getStatus();
 * <p/>
 * Copyright: Copyright (c) 2016年06月29日 19:24
 * <p/>
 * Company:
 * <p/>
 *
 * @author Kent
 * @version 1.0.0
 */
public class ResponseWrapper extends HttpServletResponseWrapper {

    private ByteArrayOutputStream buffer;

    private ServletOutputStream out;

    public void setWriter(PrintWriter writer) {
        this.writer = writer;
    }

    public ByteArrayOutputStream getBuffer() {
        return buffer;
    }

    public void setBuffer(ByteArrayOutputStream buffer) {
        this.buffer = buffer;
    }

    public ServletOutputStream getOut() {
        return out;
    }

    public void setOut(ServletOutputStream out) {
        this.out = out;
    }

    private PrintWriter writer;

    public ResponseWrapper(HttpServletResponse response) throws IOException {
        super(response);

        buffer = new ByteArrayOutputStream();   // 真正存储数据的流
        out = new WapperedOutputStream(buffer);
        writer = new PrintWriter(new OutputStreamWriter(buffer, this.getCharacterEncoding()));
    }

    /**
     * 重载父类获取outputstream的方法
     */
    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        return out;
    }

    /**
     * 重载父类获取writer的方法
     */
    @Override
    public PrintWriter getWriter() throws UnsupportedEncodingException {
        return writer;
    }

    /**
     * 重载父类获取flushBuffer的方法
     */
    @Override
    public void flushBuffer() throws IOException {
        if (out != null) {
            out.flush();
        }
        if (writer != null) {
            writer.flush();
        }
    }

    @Override
    public void reset() {
        buffer.reset();
    }

    /**
     * 将out、writer中的数据强制输出到WapperedResponse的buffer里面，否则取不到数据
     */
    public byte[] getResponseData() throws IOException {
        flushBuffer();
        return buffer.toByteArray();
    }

}
